import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

const getDefaultReportData = () => ({})
const getDefaultComparisonData = () => ({
    half_hour: null,
    day: null,
    month: null
})

export const useReportStore = defineStore('report', () => {
    const companyReportData = ref(getDefaultReportData())
    const lastCompanyReportData = ref(getDefaultReportData())
    const comparisonData = ref(getDefaultComparisonData())
    const unkownWaterData = ref({})
    const fourWeekData = ref([
        { name: '本周', data: [] },
        { name: '前一周', data: [] },
        { name: '前二周', data: [] },
        { name: '前三周', data: [] }
    ])

    // 图表状态
    const chartState = ref({
        chartType: 'bar',
        period: 'day',
        comparison: 'none',
        comparisonDate: null
    })
    // 修改图表状态
    function setChartState(state) {
        chartState.value = state
    }

    function updateReportData(type, data, total, isLastPeriod = false) {
        const targetStore = isLastPeriod ? lastCompanyReportData : companyReportData
        targetStore.value[type] = {
            total,
            data: [...data]
        }
    }

    function updateComparisonData(type, data) {
        console.log('comparisonData', comparisonData.value);
        console.log('updateComparisonData', type, data);
        comparisonData.value[type] = [...data]
        console.log('comparisonData', comparisonData.value);
    }

    // 添加清除对比数据的方法
    function clearComparisonData() {
        comparisonData.value = getDefaultComparisonData()
    }

    function updateFourWeekData(weekIndex, data) {
        fourWeekData.value[weekIndex].data = [...data]
    }

    function updateUnKownWaterReportData(type, data) {
        unkownWaterData.value[type] = [...data]
    }

    function resetReportData() {
        companyReportData.value = getDefaultReportData()
        lastCompanyReportData.value = getDefaultReportData()
        comparisonData.value = getDefaultComparisonData()
        fourWeekData.value = fourWeekData.value.map(week => ({
            ...week,
            data: []
        }))
        unkownWaterData.value = {}
    }

    const getReportDataList = computed(() =>
        (type, isLastPeriod = false) => {
            const store = isLastPeriod ? lastCompanyReportData.value : companyReportData.value
            return { ...store[type] }
        }
    )

    const getComparisonData = computed(() =>
        (type) => comparisonData.value[type] || []
    )

    return {
        companyReportData,
        lastCompanyReportData,
        comparisonData,
        fourWeekData,
        getReportDataList,
        getComparisonData,
        unkownWaterData,
        chartState,
        setChartState,
        updateUnKownWaterReportData,
        updateReportData,
        updateComparisonData,
        updateFourWeekData,
        resetReportData,
        clearComparisonData, // 导出新添加的方法
    }
})